<!-- 组织架构模块主页 -->
<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <tree-tools :tree-node="company" :is-root="true" @addDepts="addDepts" />
        <el-tree :data="departs" default-expand-all :expand-on-click-node="false">
          <!-- 说明el-tree里面的这个内容 就是插槽内容 => 填坑内容  => 有多少个节点循环多少次 -->
          <!-- v-slot 是 tree组件传给每个节点的插槽的内容的数据 -->
          <!-- 顺序一定是先执行v-slot的赋值再去执行props的传值 -->
          <template v-slot="{ data }">
            <tree-tools :tree-node="data" @delDepts="getDepartments" @addDepts="addDepts" @editDepts="editDepts" />
          </template>
        </el-tree>
      </el-card>
      <add-dept ref="addDept" :show-dialog.sync="showDialog" :tree-node="node" @addDepts="getDepartments" />
    </div>
  </div>
</template>

<script>
import treeTools from './components/tree-tools.vue'
import { getDepartments } from '@/api/departments'
import { ListToTree } from '@/utils/index'
import addDept from './components/add-dept.vue'

export default {
  components: {
    treeTools,
    addDept
  },
  data() {
    return {
      departs: [],
      defaultProps: {
        label: 'name' // 表示 从这个属性显示内容
      },
      company: {},
      // 控制显示或隐藏窗体
      showDialog: false,
      // 当前操作的节点
      node: {},
      loading: false
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    async getDepartments() {
      this.loading = true
      const res = await getDepartments()
      console.log('组织结构数据', res)
      // treenode属性中没有id，id为undefined
      this.company = { name: res.companyName, manager: res.companyManage || '负责人', id: '' }
      this.departs = ListToTree(res.depts, '')
      this.loading = false
    },
    // 新增部门
    addDepts(node) {
      // node是当前点击的部门，该部门应被记录下来
      this.node = node
      // console.log(this.node)
      this.showDialog = true
    },
    // 编辑部门
    // 防止网速慢时弹窗显示了但数据还没请求回来，使用异步函数async/await
    async editDepts(node) {
      // 赋值操作的节点
      this.node = node
      // 父组件调用子组件弹层的方法
      await this.$refs.addDept.getDepartDetail(node.id)
      // 打开弹层
      this.showDialog = true
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px  140px;
  font-size:14px;
}
</style>
